package com.apache.ius;

import java.util.List;

import com.apache.cache.util.Validator;
import com.apache.database.constant.SpringContextLoader;
import com.apache.database.datasource.DynamicDataSource;
import com.apache.database.datasource.DynamicDataSourceHolder;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.exception.BusinessException;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.tools.DataMap;
import com.apache.tools.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CustomMethodFactory {

	protected Logger log = LoggerFactory.getLogger(getClass());

	private static CustomMethodFactory instance;

	private final String customPluginCacheKey = "group_";

	private CustomMethodFactory() {
		//filePath = Validator.getClassLoaderPath() + "config/"
	}

	public synchronized static CustomMethodFactory getInstance() {
		if (null == instance) {
			instance = new CustomMethodFactory();
		}
		return instance;
	}

	/**
	 * description: 加载配置文件
	 */
	private CustomMethodPlugin initConfig(String key) {
		//		Map<String, Object> obj = null;
		try {
			if (Validator.isNull(key)) {
				if (!IusSqlTools.getInstance().getPluginsCache().checkCacheObject("groups_open_mark")) {
					List<DataMap> list = getList("");
					if (null == list || list.isEmpty()) {
						return null;
					}
					int count = list.size();
					for (int i = 0; i < count; i++) {
						DataMap dmap = list.get(i);
						String pluginKey = String.valueOf(dmap.get("pluginFullName"));
						log.info("加载插件["+dmap.get("sysName")+"]:" + pluginKey);
						setCacheInfo(String.valueOf(dmap.get("pluginShortName")), pluginKey);
					}
					log.info("加载了["+list.size()+"]条插件数据");
					IusSqlTools.getInstance().getPluginsCache().createCacheObject("groups_open_mark", "true");
				}
				return null;
			}
			String cacheKey = customPluginCacheKey + key;
			Object value = IusSqlTools.getInstance().getPluginsCache().getCacheObjectByKey(cacheKey);
			if (null != value) {
				if (value instanceof String) {
					return getPluginsByKey(String.valueOf(value));
				} else {
					return (CustomMethodPlugin) value;
				}
			} else {
				List<DataMap> list = getList(key);
				String pluginKey = "";
				if (null != list && !list.isEmpty()) {
					for (int i = 0; i < list.size(); i++) {
						DataMap dmap = list.get(i);
						pluginKey = String.valueOf(dmap.get("pluginFullName"));
						log.info("加载插件["+dmap.get("sysName")+"]:" + pluginKey);
						setCacheInfo(String.valueOf(dmap.get("pluginShortName")), pluginKey);
					}
					log.info("加载了["+list.size()+"]条插件数据");
					return getPluginsByKey(pluginKey);
				}
				return null;
			}
			//			obj = (Map) SystemTools.getInstance().getCache("").getCacheObjectByKey(customPluginCacheKey);
			//			if (null != obj) {
			//				log.info("缓存中已存在插件数据：" + obj);
			//			} else {
			//				List<DataMap> list = getList("");
			//				int count = list.size();
			//				obj = new HashMap<>(list.size());
			//				for (int i = 0; i < count; i++) {
			//					DataMap dmap = list.get(i);
			//					String pluginKey = String.valueOf(dmap.get("pluginFullName"));
			//					log.info("正在加载:" + pluginKey);
			//					obj.put(String.valueOf(dmap.get("pluginShortName")), pluginKey);
			//					setCacheInfo(String.valueOf(dmap.get("pluginShortName")), pluginKey);
			//				}
			//				SystemTools.getInstance().getCache("").createCacheObject(customPluginCacheKey, obj);
			//			}
		} catch (BusinessException e) {
			throw e;
		} catch (Exception e) {
			log.info("注入接口失败！", e);
			return null;
		}
		//		if (null != obj && StrUtil.isNotNull(key)) {
		//			Object plugin = obj.get(key);
		//			if (plugin instanceof String) {
		//				return getPluginsByKey(String.valueOf(plugin));
		//			} else {
		//				return (CustomMethodPlugin) obj.get(key);
		//			}
		//		} else {
		//			return null;
		//		}
	}

	private List getList(String key) {
		if (!DynamicDataSource.getInstance().checkDataSource("plateform")) {
			DynamicDataSource.getInstance().addDataSource("plateform");
		}
		DynamicDataSourceHolder.putDataSource("plateform");
		IDao iusDao = (IDao) SpringContextLoader.getBean("iusPubDao");
		MethodParam param = new MethodParam("sysPluginManager", "", "", IusSqlTools.SPANCENAME);
		if (Validator.isNotNull(key)) {
			param.setParams("pluginShortName", key);
		}
		param.setOrderby("sys");
		List<DataMap> list = iusDao.select(param);
		return list;

	}

	private CustomMethodPlugin getPluginsByKey(String className) {
		if (StrUtil.isNotNull(className)) {
			try {
				log.info("开始执行插件：" + className);
				Class<?> clazz = Class.forName(className);
				CustomMethodPlugin plugin = (CustomMethodPlugin) clazz.newInstance();
				return plugin;
			} catch (Exception e) {
				log.error("加载插件失败，请检查[" + className + "]配置或者插件是否存在");
				throw new BusinessException("加载插件失败，请检查[" + className + "]配置或者插件是否存在");
			}
		}
		return null;
	}

	public void init() {
		initConfig("");
	}

	@SuppressWarnings("unchecked")
	private void setCacheInfo(String key, Object plugin) {
		String cacheKey = customPluginCacheKey + key;
		IusSqlTools.getInstance().getPluginsCache().createCacheObject(cacheKey, plugin);
		//		Map<String, Object> obj = (Map) SystemTools.getInstance().getCache("")
		//				.getCacheObjectByKey(customPluginCacheKey);
		//		if (null == obj || obj.isEmpty()) {
		//			obj = new HashMap<String, Object>();
		//		}
		//		obj.put(key, plugin);
		//		SystemTools.getInstance().getCache("").createCacheObject(customPluginCacheKey, obj);
	}

	public void setPlugins(String key, String value) {
		//		try {
		if (Validator.isNull(key) || Validator.isNull(value))
			return;
		//			Class<?> clazz = Class.forName(value.trim());
		//			setCacheInfo(key, (CustomMethodPlugin) clazz.newInstance());
		//		} catch (Exception e) {
		setCacheInfo(key, value.trim());
		//         }
	}

	public void removePlugin(String key) {
		String cacheKey = customPluginCacheKey + key;
		IusSqlTools.getInstance().getPluginsCache().removeCacheObject(cacheKey);
	}

	public CustomMethodPlugin getPluginByKey(String key) {
		return initConfig(key);
	}
}
